var Sequelize = require('sequelize');
var models = require('../../models');
var menuDao = module.exports;

menuDao.createMenu = async function(menu) {
    return models.admin.AdminMenu.create(menu);
};

menuDao.updateMenu = async function(menu) {
    return models.admin.AdminMenu.update(menu, {
        where: {
            menu_id: menu.menu_id
        }
    });
};

menuDao.getMenuById = async function(menu_id) {
    return models.admin.AdminMenu.findOne({
        where: {
            menu_id: menu_id,
            is_del: 0
        }
    });
};

menuDao.getMenuByName = async function(menu_name) {
    return models.admin.AdminMenu.findOne({
        where: {
            menu_name: menu_name,
            is_del: 0
        }
    });
};

menuDao.getParentMenu = async function() {
    return models.admin.AdminMenu.findAll({
        where: {
            parent_id: 0,
            is_del: 0
        }
    });
};

menuDao.getParentMenus = async function(ids){
    return models.admin.AdminMenu.findAll({
        where: {
            parent_id: ids,
            is_del: 0
        }
    });
};

menuDao.getAllMenu = async function () {
    return models.admin.AdminMenu.findAll({
        where: {
            is_del: 0
        }
    });
};

menuDao.getMenus = async function (keywords, offset, limit) {
    var where = {is_del:0};
    if (keywords && keywords.length != 0) {
        where = {
            is_del: 0,
            menu_name: {
                [Sequelize.Op.like]: '%'+keywords+'%'
            }
        };
    }
    return models.admin.AdminMenu.findAndCountAll({
        where: where,
        order: [
            ['parent_id', 'ASC'],
            ['menu_id', 'ASC']
        ],
        offset: Number(offset),
        limit: Number(limit),
    });
};

menuDao.destroyMenus = async function (ids) {
    return models.admin.AdminMenu.destroyMenus(ids);
};